package com.cpic.blood.admin.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Controller
public class FileUploadController {
    private final TaskExecutor taskExecutor;
    private ConcurrentHashMap<String, AtomicLong> uploadProgressMap;

    @Autowired
    public FileUploadController(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
        this.uploadProgressMap = new ConcurrentHashMap<>();
    }

    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            String uploadUrl = "http://example.com/upload";
            int numThreads = 4;

            byte[] fileBytes;
            try {
                fileBytes = file.getBytes();
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to read file data.");
            }

            int chunkSize = (int) Math.ceil((double) fileBytes.length / numThreads);

            for (int i = 0; i < numThreads; i++) {
                int start = i * chunkSize;
                int end = Math.min(start + chunkSize, fileBytes.length);

                byte[] chunk = new byte[end - start];
                System.arraycopy(fileBytes, start, chunk, 0, end - start);

                taskExecutor.execute(new FileUploader(chunk, uploadUrl, file.getOriginalFilename(), start));

                uploadProgressMap.put(file.getOriginalFilename(), new AtomicLong(0));
            }

            return ResponseEntity.ok("File upload started.");
        } else {
            return ResponseEntity.badRequest().body("No file provided.");
        }
    }

    @GetMapping("/progress/{filename}")
    public ResponseEntity<Long> getUploadProgress(@PathVariable String filename) {
        if (uploadProgressMap.containsKey(filename)) {
            AtomicLong progress = uploadProgressMap.get(filename);
            return ResponseEntity.ok(progress.get());
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    private class FileUploader implements Runnable {
        private final byte[] fileChunk;
        private final String uploadUrl;
        private final String filename;
        private final int start;

        public FileUploader(byte[] fileChunk, String uploadUrl, String filename, int start) {
            this.fileChunk = fileChunk;
            this.uploadUrl = uploadUrl;
            this.filename = filename;
            this.start = start;
        }

        @Override
        public void run() {
            try {
                // 在此处执行文件上传逻辑
                URL url = new URL(uploadUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setDoOutput(true);
                conn.setRequestMethod("POST");

                String boundary = "===" + System.currentTimeMillis() + "===";
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes("--" + boundary + "\r\n");
                dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n");
                dos.writeBytes("Content-Type: application/octet-stream\r\n");
                dos.writeBytes("\r\n");

                dos.write(fileChunk);

                dos.writeBytes("\r\n");
                dos.writeBytes("--" + boundary + "--\r\n");

                dos.flush();
                dos.close();

                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    System.out.println("File uploaded successfully.");
                } else {
                    System.out.println("File upload failed with response code: " + responseCode);
                }
                conn.disconnect();

                // 模拟上传进度更新
                for (int i = 0; i < fileChunk.length; i++) {
                    // 每上传一个字节，增加进度
                    uploadProgressMap.get(filename).incrementAndGet();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}